import java.util.*;

public class BattleshipInterface {
	
	//This class represents the user interface for the game
	
	public void run(BattleshipGame game) {
		Scanner userinput = new Scanner(System.in);
		System.out.println("Welcome to Battleship!");
		System.out.println("===========================");
		System.out.println();
		
        boolean cheat = false; //show the ships when true
        
        //---------USER INITIALIZATION BLOCK--------
        System.out.print("Enter your name and press ENTER: ");
        String name = userinput.nextLine();
        
        String battleship, cruiser, destroyer, tug;
        boolean validBoard = false;
        while(!validBoard){
	        System.out.print("Enter Battleship location and direction: (e.g. 2,2,H): ");
				battleship = userinput.nextLine();
	
			if (battleship.equals("*")) {
				//Random placement class call
				destroyer = "*";
				cruiser = "*";
				tug = "*";
			}else{
				System.out.print("Enter Destroyer location and direction: (e.g. 2,3,H): ");
					destroyer = userinput.nextLine();
				System.out.print("Enter Cruiser location and direction: (e.g. 2,4,H): ");
					cruiser = userinput.nextLine();
				System.out.print("Enter Tug location and direction: (e.g. 2,5,H): ");
					tug = userinput.nextLine();
			}
			validBoard = game.userInitialization(name, battleship, destroyer, cruiser, tug);
			if (!validBoard){
				System.out.println("\nSorry, " + name + ", you have incorrectly placed a piece on the board, please retry:");
			}
		}
		System.out.println();
        //---------END USER INIT BLOCK--------------
		
		while (!game.isWon()) {	
			// print the game
			game.printGameBoard(cheat);
			System.out.print("Please Enter Target Coordinates (e.g. 4,3): ");
			String move = userinput.nextLine();
			int movex, movey;
			movex = -2;
			movey = -2;
			
			StringTokenizer tokenizer = new StringTokenizer(move, ",");
			if (tokenizer.countTokens() == 2){
				try{
				//Tries to parse the string tokens into integers
				movex = Integer.parseInt(tokenizer.nextToken());
				movey = Integer.parseInt(tokenizer.nextToken());
				}catch (Exception e) {/*Doesn't handle exceptions*/}
			}
			
			// Cheat code: displays entire board layout
			if (movex == -1 && movey == -1) {
				cheat = true;
			}
			else{
			// Parse the move
			cheat = false;
		    //Treat X as horizonal and Y as vertical, function doe the opposite
			String result = game.move(movey, movex);
			System.out.println("\n" + name + result + "\n" );
			}
		}

	}
	
	public static void main(String[] args) {
		//create a game, a game interface and launch the game
		BattleshipGame game = new BattleshipGame();
		BattleshipInterface userInterface = new BattleshipInterface();
		userInterface.run(game);	
	}
}
